<template>
    <div class="app-container">
        <el-divider content-position="left">编辑作业/试卷</el-divider>
        <el-form :model="form" ref="form" :rules="rules" label-width="110px">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="试卷/作业名称" prop="testpaperName">
                        <el-input v-model="form.testpaperName" clearable style="width:70%"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="总分数" prop="totalPoints">
                        <el-input v-model="form.totalPoints" clearable style="width:70%" :disabled="true"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="分类" prop="classify">
                        <el-select v-model="form.classify" clearable filterable style="width:70%">
                            <el-option value="1" label="日常作业"></el-option>
                            <el-option value="2" label="考试试卷"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="适用专业" prop="major">
                        <el-select v-model="form.major" clearable filterable style="width:70%">
                            <el-option v-for="item in majorList" :label="item.subjectName + ''" placeholder="班级专业"
                                :value="item.id + ''" :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="适用科目" prop="subjectId">
                        <el-select v-model="form.subjectId" clearable filterable size="small" style="width: 70%">
                            <el-option v-for="dict in subjectList" :key="dict.id" :label="dict.subjName" :value="dict.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="适用年级" prop="grade">
                        <el-select v-model="form.grade" clearable filterable style="width:70%">
                            <el-option v-for="dict in classGradeList" placeholder="班级年级" :key="dict.dictValue"
                                :label="dict.dictLabel" :value="dict.dictValue + ''"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-if="form.classify==2">
                <el-col :span="8">
                    <el-form-item label="考试时长" prop="duration">
                        <el-input placeholder="请输入内容" v-model.number="form.duration" style="width:70%">
                            <template slot="append">分钟</template>
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- <el-form-item label="试题添加">
                <el-button   size="mini" icon="el-icon-plus" type="primary" @click="choicePaperHandle">添加试题</el-button>
                <el-button   size="mini" icon="el-icon-files" type="primary" @click="importData">批量导入</el-button>
            </el-form-item> -->
            <el-divider content-position="left">题目部分</el-divider>

            <el-row :gutter="20">
                <el-col :span="16">
                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                            <span>作业/试卷信息</span>
                            <el-button style="float: right; margin-left: 5px;" size="mini" icon="el-icon-plus"
                                type="primary" @click="choicePaperHandle">添加试题</el-button>
                            <el-button style="float: right; " size="mini" icon="el-icon-files" type="primary"
                                @click="importData">批量导入</el-button>
                            <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
                        </div>
                        <div v-if="questionList.length > 0">
                            <div v-for="item, index in questionList" :key="item.id" class="text item"
                                style="margin-bottom: 5px;">
                                <el-card class="box-card" :id="'question-'+index">
                                    <div slot="header" class="clearfix">
                                        <span style="padding: 0px 10px;border-left: 4px solid #1890ff;">
                                            <label>{{ index + 1 }}. </label>
                                            <label v-if="item.questionsType == 1">单选题</label>
                                            <label v-if="item.questionsType == 2">多选题</label>
                                            <label v-if="item.questionsType == 3">判断题</label>
                                            <label v-if="item.questionsType == 4">填空题</label>
                                            <label v-if="item.questionsType == 5">问答题</label>
                                        </span>
                                        <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                                          <el-link style="float: right;font-size: 18px; margin-left: 8px;" icon="el-icon-edit"
                                                   @click="edit(item.id)"></el-link>
                                        </el-tooltip>
                                        <el-tooltip class="item" effect="dark" content="删除" placement="top">
                                            <el-link style="float: right;font-size: 18px; margin-left: 8px;" icon="el-icon-delete"
                                                @click="deleteTitle(item, index)"></el-link>
                                        </el-tooltip>
                                        <el-tooltip class="item" effect="dark" content="上移" placement="top">
                                            <el-link style="float: right; margin-left: 5px;font-size: 18px;"
                                                icon="el-icon-upload2" v-if="index > 0" @click="upMove(item, index)"></el-link>
                                        </el-tooltip>
                                        <el-tooltip class="item" effect="dark" content="下移" placement="top">
                                            <el-link style="float: right;font-size: 18px; " icon="el-icon-download"
                                                v-if="index < questionList.length - 1" @click="downMove(item, index)"></el-link>
                                        </el-tooltip>
                                        <p style="padding: 0px 10px">{{ item.questionsName }}</p>
                                    </div>
                                    <div class="text item" v-if="item.questionsType == 1 || item.questionsType == 2">
                                        <div v-html="getOptionsTxt(item)" class="txtDiv"></div>
                                    </div>
                                    <div v-if="item.analysis">
                                        <el-collapse accordion style="padding: 0px 10px;margin-bottom: 10px;">
                                            <el-collapse-item title="查看解析">
                                                <div>{{ item.analysis }}</div>
                                            </el-collapse-item>
                                        </el-collapse>
                                    </div>
                                    <div>
                                        <span style="padding: 5px 10px;color:#44b913"><label>正确答案：{{ getUnit(item)
                                        }}</label></span>
                                    </div>
                                    <div>
                                        <p style="padding: 0px 10px">
                                            <span style="font-size:14px">本题分值：</span>
                                            <el-input placeholder="请输入内容" suffix-icon="el-icon-edit" size="mini"
                                                style="width:100px" v-model="item.scoresScore"> </el-input>
                                        </p>


                                        <!-- <el-input-number v-model="item.scoresScore" controls-position="right" size="mini"  :min="1" :max="100"></el-input-number> -->
                                    </div>
                                </el-card>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="8">
                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                            <span>试题列表</span>
                        </div>
                        <div v-for="item, index in classifyList" :key="item.index">
                            <div v-if="item.data.length > 0" :style="index > 0 ? 'margin-top: 10px;' : ''">
                                <div class="titleClsDiv">
                                    <el-row>{{ item.typeName }}</el-row>
                                    <el-row>
                                        <el-col :span="3" style="line-height: 28px;">
                                            {{ item.countScore }}分
                                        </el-col>
                                        <el-col :span="3" style="line-height: 28px;">
                                            {{ item.data.length }}题
                                        </el-col>
                                        <el-col :span="18">
                                            每题分值：<el-input placeholder="请输入分值" v-model="item.avgScore"
                                                @change="updateTypeScore(item)" suffix-icon="el-icon-edit" size="mini"
                                                style="width:150px"> </el-input>
                                        </el-col>
                                    </el-row>
                                </div>
                                <el-row class="qindexDiv">
                                    <el-tag effect="plain" type="info" v-for="tag in item.data" @click="scrollToposition('question-'+(tag.index-1))"
                                        :key="tag.index">{{ tag.index }}</el-tag>
                                </el-row>
                            </div>

                        </div>
                    </el-card>
                </el-col>
            </el-row>
            <!-- <el-table  ref="multipleTable" :data="questionList" v-if="questionList && questionList.length>0" height="500">
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-form label-position="left" class="demo-table-expand" label-width="100">
                            <el-row>
                                <el-col :span="12">
                                    <el-form-item label="试卷题目">
                                        <span>{{ scope.row.questionsName }}</span>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="试卷类型">
                                        <label v-if="scope.row.questionsType==1">单选题</label>
                                        <label v-if="scope.row.questionsType==2">多选题</label>
                                        <label v-if="scope.row.questionsType==3">判断题</label>
                                        <label v-if="scope.row.questionsType==4">填空题</label>
                                        <label v-if="scope.row.questionsType==5">问答题</label>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-form-item label="选项" v-if="scope.row.questionsType==1 || scope.row.questionsType==2">
                                <div v-html="getOptionsTxt(scope.row)" class="txtDiv" style="margin-left: 100px;"></div>
                            </el-form-item>
                            <el-form-item label="答案">
                                <span>{{ getUnit(scope.row) }}</span>
                            </el-form-item>
                        </el-form>
                    </template>
                    </el-table-column>
                <el-table-column label="序号" type="index" width="50"> </el-table-column>
                <el-table-column label="专业" align="center" prop="major"  width="150" :show-overflow-tooltip="true" >
                <template slot-scope="scope">
                    {{ getMajorLable(scope.row.major) }}
                </template>
                </el-table-column>
                <el-table-column label="科目" align="center" width="100" prop="subjects" :show-overflow-tooltip="true" >
                <template slot-scope="scope">
                    {{ getSubjectLable(scope.row.subjects) }}
                </template>
                </el-table-column>
                <el-table-column label="试题类型" align="center"  width="100" sortable prop="questionsType" :show-overflow-tooltip="true" >
                <template slot-scope="scope">
                    <label v-if="scope.row.questionsType==1">单选题</label>
                    <label v-if="scope.row.questionsType==2">多选题</label>
                    <label v-if="scope.row.questionsType==3">判断题</label>
                    <label v-if="scope.row.questionsType==4">填空题</label>
                    <label v-if="scope.row.questionsType==5">问答题</label>
                </template>
                </el-table-column>
                <el-table-column label="试题题目" align="center" prop="questionsName"  :show-overflow-tooltip="true" >
                </el-table-column>

                <el-table-column label="年級" align="center" prop="grade" width="160">
                <template slot-scope="scope">
                    {{ selectDictLabel(classGradeList, scope.row.grade) }}
                </template>
                </el-table-column>
                <el-table-column label="默认分数" align="center" prop="sore" width="160">
                </el-table-column>
                <el-table-column label="自定义分数" align="center" prop="scoresScore" width="160">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.scoresScore" controls-position="right" size="mini"  :min="1" :max="100"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" prop="sore" width="100">
                    <template slot-scope="scope">

                        <el-link icon="el-icon-caret-top" v-if="scope.$index>0" @click="upMove(scope.row,scope.$index)"></el-link>
                        <el-link icon="el-icon-caret-bottom" v-if="scope.$index<questionList.length-1" @click="downMove(scope.row,scope.$index)"></el-link>
                    </template>
                </el-table-column>
            </el-table> -->
        </el-form>
        <div style="text-align: center;margin-top: 10px;">
            <el-button type="primary" @click="onSubmit" :loading="submitLoading">提 交</el-button>
            <el-button @click="cancel">返 回</el-button>
        </div>

        <el-dialog title="选择题目" :visible.sync="editPaperVisible" width="60%">
            <questionListComponent @getQuestionList="getQuestionList" @closeQuestionList="closeQuestionList"
                :dataList="questionList"></questionListComponent>
        </el-dialog>

        <el-dialog title="导入试题信息" :visible.sync="importVisible" width="400px">
            <el-upload v-loading="importLoading" class="upload-demo" drag :action="upload.url" :headers="upload.headers"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :file-list="fileList">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip"><el-link type="primary" :href="templateDowloadUrl">模板下载</el-link>
                </div>
            </el-upload>
        </el-dialog>

      <el-dialog
        title="题目修改"
        :visible.sync="dialogVisible"
        width="60%"
        :before-close="handleClose">
        <div class="app-container">
          <el-form :model="this.form1" ref="form" :rules="rules" label-width="110px">
            <el-form-item label="题目" prop="questionsName">
              <el-input type="textarea" :rows="2" v-model="form1.questionsName" :placeholder="form1.placeholder" style="width: 90%" @change="fillContentInput"></el-input>
            </el-form-item>
            <el-form-item label="答案选项" v-if="form1.questionsType=='1' || form1.questionsType=='2'">
              <div v-for="item in form1.optionList" :key="item.optIdx">
                <el-row>
                  <el-col :span="2">
                    <el-tag>{{ item.optIdx }}</el-tag>
                  </el-col>
                  <el-col :span="22">
<!--                    <editor :refName="'quillEditor'+item.optIdx" :value="item.optTxt" @input="updateContext" :itemData="item" :options="toolbarOptions"></editor>-->
                    <editor :value="item.optTxt" :itemData="item" @input="updateContext"></editor>
<!--                    <span>hhhhh</span>-->
                  </el-col>
                </el-row>
              </div>
            </el-form-item>
            <el-form-item label="正确答案" v-if="form1.questionsType=='1'">
              <el-radio  v-for="item in form1.unitList" v-model="form1.unit" :key="item.optIdx" :label="item.optIdx">{{ item.optIdx }}</el-radio>
            </el-form-item>
            <el-form-item label="正确答案" v-if="form1.questionsType=='2'">
              <el-checkbox  v-for="item in form1.unitList" v-model="item.isRight" :key="item.optIdx" >{{ item.optIdx }}</el-checkbox>
            </el-form-item>
            <el-form-item label="正确答案" v-if="form1.questionsType=='3'">
              <el-radio  v-for="item in form1.unitList" v-model="form1.unit" :key="item.optIdx" :label="item.optIdx">{{ item.optTxt }}</el-radio>
            </el-form-item>
            <el-form-item label="正确答案" v-if="form1.questionsType=='4'">
              <el-input style="width:150px;margin-right: 5px;" clearable v-for="item in form1.unitList" :key="item.optIdx" v-model="item.optTxt"></el-input>
            </el-form-item>
            <el-form-item label="正确答案" v-if="form1.questionsType=='5'">
              <el-input type="textarea" :rows="3" placeholder="请输入问答题答案" v-model="form1.unit"> </el-input>
            </el-form-item>
            <el-form-item label="解析">
              <el-input type="textarea" :rows="3" placeholder="请输入解析内容" v-model="form1.analysis"> </el-input>
            </el-form-item>
            <el-form-item label="题目分数" prop="sore">
              <el-input-number v-model="form1.sore"  :min="1" :max="100" label="描述文字"></el-input-number>
            </el-form-item>
          </el-form>
          <div style="text-align: center;">
            <el-button type="primary" @click="onSubmit1" :loading="submitLoading">提 交</el-button>
            <el-button @click="cancel">返 回</el-button>
          </div>
        </div>
      </el-dialog>

    </div>
</template>

<script>
import { findBaseSubjectPageList } from "@/api/baseData/profession";
import { subjectList } from "@/api/educational/subject.js";
import { addQuestions, updateQuestions, getQuestionsDetails } from "@/api/studentInfo/questions";
import { addTestPaper, updateTestPaper, examinationDetails } from "@/api/studentInfo/taskAndPaper";
import questionListComponent from "../../components/exam/questionListComponent";
import { getToken } from '@/utils/auth'
import 'katex/dist/katex.css';
import Editor from "../../../components/Editor/index";

export default {
    name: "editQusetions",
    components: {
      Editor,
        questionListComponent

    },
    data() {
        return {
          dialogVisible:false,
            importLoading: false,
            templateDowloadUrl: process.env.VUE_APP_BASE_API + "/school/file/examWorkTemp.docx",
            upload: {
                url: process.env.VUE_APP_BASE_API + '/tExamSubject/tExamSubjectWord',
                headers: { Authorization: "Bearer " + getToken() },
            },
            importVisible: false,
            fileList: [],
            submitLoading: false,
            editPaperVisible: false,
            majorList: [],//专业
            subjectList: [],//科目
            classGradeList: [],
            form: {
                grade: null,
                subjectId: null,
                major: null,
                classify: null,
                totalPoints: null,
                testpaperName: null,
                duration: null,
                examCorrelationsList: [],
                examSubjectList: [],
              //修改题目

            },
            form1:{
              grade: null,
              subjectId: null,
              major: null,
              classify: null,
              totalPoints: null,
              testpaperName: null,
              duration: null,
              examCorrelationsList: [],
              examSubjectList: [],
              questionsName:null,
              options:[],
              optionList:[],
              unitList:null,
              unit:null,
              isRight:null
            },
            checkList:[
              {optIdx:"A",isRight:false},
              {optIdx:"B",isRight:false},
              {optIdx:"C",isRight:false},
              {optIdx:"D",isRight:false},
            ],
            toolbarOptions : [
              ["bold", "italic", "underline", "strike"],       // 加粗 斜体 下划线 删除线
              ["blockquote", "code-block"],                    // 引用  代码块
              ["clean"],                                       // 清除文本格式
              ["link", "image", "video"],                       // 链接、图片、视频
              ['formula']  //公式
            ],
            //修改题目 ↑↑↑
            rules: {
                testpaperName: [
                    { required: true, message: "请填写试卷/作业名称", trigger: "change" }
                ],
                totalPoints: [
                    { required: true, message: "请填写总分数", trigger: "change" }
                ],
                classify: [
                    { required: true, message: "请选择分类", trigger: "change" }
                ],
                major: [
                    { required: true, message: "请选择适用专业", trigger: "change" }
                ],
                subjectId: [
                    { required: true, message: "请选择适用科目", trigger: "change" }
                ],
                grade: [
                    { required: true, message: "请选择适用年级", trigger: "change" }
                ],
                duration:[
                    { required: true, message: "请填写时长", trigger: "change" },
                    { type: 'number', message: '时长必须为数字值',trigger: "change"  },
                ],
              //修改题目
              questionsType: [
                { required: true, message: "请选择试题类型", trigger: "change" }
              ],
              subjects: [
                { required: true, message: "请选择试题适用科目", trigger: "change" }
              ],
              questionsName:[
                { required: true, message: "题目不能为空", trigger: "change" }
              ],
              sore:[
                { required: true, message: "请选择题目分数", trigger: "change" }
              ]
            },
            id: null,
            questionList: [],
            classifyList: [],
        };
    },
    created() {
        this.id = this.$route.query.id
        const that = this
        if (this.id) {
            examinationDetails(this.id).then(resp => {
                if (!resp.data) {
                    that.$message({ message: '没有查询到您要的试题', type: 'warning' });
                    return
                }
                this.form = resp.data
                this.questionList = resp.data.examSubjectList
                this.questionClassify()

            })
        }
        this.getMajorList()
        this.getSubjectList()
        this.getDicts("class_grade").then(response => {
            this.classGradeList = response.data;
        });


    },
    methods: {
      //修改题目
      updateContext(val,item){
        console.log(val,item)
        item.optTxt = val
      },
      fillContentInput(){

        if(this.form.questionsType==4){
          //填空内容输入
          let titlsFlags = this.form.questionsName.match(/{}/g)
          if(titlsFlags){
            let answers=[]
            console.log(titlsFlags.length)
            for(let i=1;i<=titlsFlags.length;i++){
              answers.push({
                optIdx:i, optTxt:"第"+i+"个空位答案"
              })
            }
            console.log(answers)
            this.form.unitList=answers

          }else{
            this.form.unitList=[]
          }
          console.log(this.form)
        }

      },
      qusetionSelected(){

        //选择题型
        if(this.form.questionsType=='1'){
          //单选
          this.xian = 1;
          this.singleChoiceHandle('1')
        }
        if(this.form.questionsType=='2'){
          //多选
          this.xian = 2;
          this.singleChoiceHandle('2')
        }
        if(this.form.questionsType=='3'){
          //判断
          this.judgeHandle()
        }
        if(this.form.questionsType=='4'){
          //填空题
          this.fillHandle()
        }
        if(this.form.questionsType=='5'){
          this.qAndaHandle()
        }
        console.log(this.form)
      },
      qAndaHandle(){

        //问答题
        this.form.questionsName=null,
          this.form.unitList="",
          this.form.isRight=null

      },
      fillHandle(){

        //填空题
        this.form.placeholder= '填空题的空位请用 "{}" 代提，如：13 + {} = 56',
          this.form.questionsNameL=null,
          this.form.unitList=[],
          this.form.isRight=null


      },
      judgeHandle(){

        //判断题
        this.form.questionsName=null
        this.form.unitList=[
          {optIdx:"yes", optTxt:"对", isRight:false},
          {optIdx:"wrong", optTxt:"错", isRight:false},
        ]
        this.form.isRight=null
        console.log(this.form)
      },
      resetForm(type){

        this.form={
          subjectId: this.form.subjectId,
          classify: this.form.classify,
          totalPoints: this.form.totalPoints,
          testpaperName: this.form.testpaperName,
          duration: this.form.duration,
          examCorrelationsList: [],
          examSubjectList: [],


          questionsName:null,
          major:this.form.major,
          subjects:this.form.subjects,
          grade:this.form.grade,
          options:[],
          optionList:[
            {optTxt:"第一题",optIdx:"A"},
            {optTxt:"第二题",optIdx:"B"},
            {optTxt:"第三题",optIdx:"C"},
            {optTxt:"第四题",optIdx:"D"}
          ],
          unitList:[
            {optIdx:"A",isRight:false},
            {optIdx:"B",isRight:false},
            {optIdx:"C",isRight:false},
            {optIdx:"D",isRight:false}
          ],
          unit:null,
          isRight:null,
          questionsType:type,
        }
      },
      singleChoiceHandle(type){

        //选择单选题
        this.form.questionsName=null
        this.form.optionList=[
          {optTxt:"第一题",optIdx:"A"},
          {optTxt:"第二题",optIdx:"B"},
          {optTxt:"第三题",optIdx:"C"},
          {optTxt:"第四题",optIdx:"D"},

        ]
        this.form.unitList=[
          {optIdx:"A",isRight:false},
          {optIdx:"B",isRight:false},
          {optIdx:"C",isRight:false},
          {optIdx:"D",isRight:false},
        ]
        this.form.unit=null


        console.log(this.form.unitList)
        // this.$forceUpdate()
      },
      edit(id){
        // alert(id)
        this.dialogVisible = true;
        getQuestionsDetails(id).then(resp=>{ // 获取试题详细信息
          if(!resp.data){ // 如果获取到的数据为空
            this.$message({ message: '没有查询到您要的试题', type: 'warning' }); // 显示警告信息
            return; // 结束函数
          }

          this.form1 = resp.data
          // this.form = resp.data; // 将获取到的数据赋值给 this.form

          // 根据试题类型对 this.form.optionList 和 this.form.unitList 进行不同的赋值操作
          if(this.form1.questionsType==1) {
            console.log(resp.data.options)
            // this.form.optionList = JSON.parse(resp.data.options); // 将 resp.data.options 转换为 JSON 格式并赋值给 this.form.optionList
            this.$set(this.form1,'optionList',JSON.parse(resp.data.options))
            this.form1.unitList = [
              {optIdx: "A", isRight: false},
              {optIdx: "B", isRight: false},
              {optIdx: "C", isRight: false},
              {optIdx: "D", isRight: false},
            ]; // 将 this.form.unitList 初始化为一个包含四个选项的对象数组
          }
          if(this.form1.questionsType==2){
            this.$set(this.form1,'optionList',JSON.parse(resp.data.options)); // 将 resp.data.options 转换为 JSON 格式并赋值给 this.form.optionList
            this.$set(this.form1,'unitList',JSON.parse(resp.data.unit)); // 将 resp.data.unit 转换为 JSON 格式并赋值给 this.form.unitList
          }
          if(this.form1.questionsType==3){
            this.form1.unitList=[
              {optIdx:"yes", optTxt:"对", isRight:false},
              {optIdx:"wrong", optTxt:"错", isRight:false},
            ]; // 将 this.form.unitList 初始化为一个包含“对”和“错”两个选项的对象数组
          }
          if(this.form1.questionsType==4){
            this.$set(this.form1,'unitList',JSON.parse(resp.data.unit)); // 将 resp.data.unit 转换为 JSON 格式并赋值给 this.form.unitList
          }
          if(this.form1.questionsType==5){
            this.$set(this.form1,'unit',JSON.parse(resp.data.unit)); // 将 resp.data.unit 转换为 JSON 格式并赋值给 this.form.unit
            // this.form.unit=JSON.parse(resp.data.unit)
          }
          console.log(this.form1); // 输出 this.form 对象的值
        })
      },
      onSubmit1(){

        this.submitLoading = true
        console.log(this.form)
        if(this.form1.questionsType==1 || this.form1.questionsType==2){
          this.form1.options = JSON.stringify(this.form1.optionList)
        }
        if(this.form1.questionsType==2){
          this.form1.unit = JSON.stringify(this.form1.unitList)
          if(this.xian == 2){
            this.form1.unit = JSON.stringify(this.checkList)
          }
        }
        if(this.form1.questionsType!=1 && this.form1.questionsType!=2){
          //处理选择题，其他题目都没有选项
          this.form1.options = null
        }
        if(this.form1.questionsType==4 || this.form1.questionsType==5){
          this.form1.unit= JSON.stringify(this.form1.unitList)
        }
        const _this = this
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(this.id){
              updateQuestions(this.form1).then(resp => {
                this.submitLoading = false
                _this.msgSuccess("更新成功");
                // _this.$router.push("/educational/exam/questions")
                this.$router.go(0)
              });
            }else{
              addQuestions(this.form).then(resp=>{
                this.submitLoading = false
                this.$confirm('提交成功，是否停留在该页面', "警告", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "success"
                }).then(() => {
                  _this.form.questionsType
                  _this.qusetionSelected()
                }).catch(function() {
                  this.dialogVisible = false;
                });
              })
            }

          }else{
            this.submitLoading = false
          }

        })
      },
      //修改题目↑↑↑
        deleteTitle(item, index) {

            this.questionList.splice(index, 1)
            this.questionClassify()
            this.msgSuccess("成功删除");
        },
        //统一修改不同类型题目的分数
        updateTypeScore(data) {

            this.questionList.forEach(item => {
                if (item.questionsType == data.questionsType) {
                    console.log(data.avgScore)
                    item.scoresScore = data.avgScore
                }
            })

            console.log('------------------')
            console.log(data)
            console.log(this.questionList)
            console.log(this.classifyList)
            if (data.questionsType == 1) {
                this.classifyList.map(item => {
                    if (item.questionsType == 1) {
                        item.avgScore = data.avgScore
                        item.countScore = item.data.length * item.avgScore
                    }
                })
            }
            if (data.questionsType == 2) {
                this.classifyList.map(item => {
                    if (item.questionsType == 2) {
                        item.avgScore = data.avgScore
                        item.countScore = item.data.length * item.avgScore
                    }
                })
            }
            if (data.questionsType == 3) {
                this.classifyList.map(item => {
                    if (item.questionsType == 3) {
                        item.avgScore = data.avgScore
                        item.countScore = item.data.length * item.avgScore
                    }
                })
            }
            if (data.questionsType == 4) {
                this.classifyList.map(item => {
                    if (item.questionsType == 4) {
                        item.avgScore = data.avgScore
                        item.countScore = item.data.length * item.avgScore
                    }
                })
            }
            if (data.questionsType == 5) {
                this.classifyList.map(item => {
                    if (item.questionsType == 5) {
                        item.avgScore = data.avgScore
                        item.countScore = item.data.length * item.avgScore
                    }
                })
            }
            let totalCount = 0
            this.classifyList.forEach(item => {
                totalCount += Number(item.countScore)
            })
            this.form.totalPoints = totalCount
        },
        //题目分类计算
        questionClassify() {
            this.classifyList = []
            let danxuanList = []
            let duoxuanList = []
            let panduanList = []
            let tiankongList = []
            let wendaList = []
            if (this.questionList.length > 0) {
                this.questionList.forEach((item, index) => {
                    if (item.questionsType == 1) {
                        danxuanList.push({
                            index: index + 1,
                            scoresScore: item.scoresScore
                        })
                    }
                    if (item.questionsType == 2) {
                        duoxuanList.push({
                            index: index + 1,
                            scoresScore: item.scoresScore
                        })
                    }
                    if (item.questionsType == 3) {
                        panduanList.push({
                            index: index + 1,
                            scoresScore: item.scoresScore
                        })
                    }
                    if (item.questionsType == 4) {
                        tiankongList.push({
                            index: index + 1,
                            scoresScore: item.scoresScore
                        })
                    }
                    if (item.questionsType == 5) {
                        wendaList.push({
                            index: index + 1,
                            scoresScore: item.scoresScore
                        })
                    }

                })
                this.classifyList.push({
                    typeName: "单选题",
                    data: danxuanList,
                    questionsType: 1,
                    countScore: this.computeScore(danxuanList),
                    avgScore: null,
                })
                this.classifyList.push({
                    typeName: "多选题",
                    questionsType: 2,
                    data: duoxuanList,
                    countScore: this.computeScore(duoxuanList),
                    avgScore: null,
                })
                this.classifyList.push({
                    typeName: "判断题",
                    questionsType: 3,
                    data: panduanList,
                    countScore: this.computeScore(panduanList),
                    avgScore: null,
                })
                this.classifyList.push({
                    typeName: "填空题",
                    questionsType: 4,
                    data: tiankongList,
                    countScore: this.computeScore(tiankongList),
                    avgScore: null,
                })
                this.classifyList.push({
                    typeName: "问答题",
                    questionsType: 5,
                    data: wendaList,
                    countScore: this.computeScore(wendaList),
                    avgScore: null,
                })

                this.form.totalPoints = this.computeScore(danxuanList) + this.computeScore(duoxuanList)
                    + this.computeScore(panduanList) + this.computeScore(tiankongList) + this.computeScore(wendaList)
            }

        },
        //计算分数
        computeScore(array) {
            let count = 0;
            if (array.length > 0) {
                array.forEach(item => {
                    count = Number(count) + Number(item.scoresScore)
                })
            }
            return count
        },
        upMove(item, index) {
            //上移
            this.questionList.splice(index - 1, 0, item);
            this.questionList.splice(index + 1, 1);
            this.questionClassify()
            this.msgSuccess("成功上移");
        },
        downMove(item, index) {
            //下移
            this.questionList.splice(index + 2, 0, item);
            this.questionList.splice(index, 1);
            this.questionClassify()
            this.msgSuccess("成功下移");
        },
        importData() {

            if (!this.form.grade || !this.form.major || !this.form.subjectId) {
                this.$message({
                    message: '上传文件时【适用专业】/【适用科目】/【适用年级】不能为空',
                    type: 'warning'
                });
                return
            }
            this.upload.url = process.env.VUE_APP_BASE_API + '/tExamSubject/tExamSubjectWord?grade='
                + this.form.grade + '&major=' + this.form.major + '&subjectId=' + this.form.subjectId,
                //打开导入页面
                this.importVisible = true
            this.fileList = []
            this.importLoading = false
        },
        handleAvatarSuccess(res, file) {

            this.fileList.push(file)
            if (res.code == 200) {
                this.$message({ message: '导入成功', type: 'success' });
                this.questionList.push(...res.data)
                this.questionClassify()
                this.importLoading = false
                this.importVisible = false
            } else {
                this.$message.error(res.message);
                this.importLoading = false
                this.importVisible = false
            }
            this.fileList = []
        },
        beforeAvatarUpload(file) {

            this.importLoading = true
            console.log(file.name.lastIndexOf('.docx'))
            if (file.name.lastIndexOf('.docx') < 0 && file.name.lastIndexOf('.DOCX') < 0) {
                this.$message({
                    message: '上传文件只能是.docx文件',
                    type: 'warning'
                });
                return false
            }
            console.log(file, 'beforefile')

        },
        getUnit(row) {
            let optTxt = ''
            if (row.questionsType == 2) {
                JSON.parse(row.unit).forEach(item => {
                    if (item.isRight) {
                        optTxt += item.optIdx + '\n'
                    }
                })
            } else if (row.questionsType == 4) {
                JSON.parse(row.unit).forEach(item => {
                    optTxt += item.optTxt + '\n'
                })
            }
            else if (row.questionsType == 3) {
                row.unit=='yes'?optTxt="正确":optTxt="错误"
            }
            else {
                optTxt = row.unit
            }
            return optTxt;
        },
        getOptionsTxt(row) {
            let optTxt = ''
            var reg = /<[^>]+>/g;


            JSON.parse(row.options).forEach(item => {
                if (reg.test(item.optTxt)) {
                    optTxt += '<p style="padding: 10px;"><span>' + item.optIdx + '：</span>' + item.optTxt.substring(item.optTxt.indexOf("<p>") + 3)
                } else {
                    optTxt += '<p style="padding: 10px;">' + item.optIdx + '：' + item.optTxt + '</p>'
                }

            })
            return optTxt
        },
        getQuestionList(data, showVisible) {

            this.questionList = data
            this.questionList.forEach(item => {
                item.scoresScore = Number(item.sore)
                this.$set(item, 'scoresScore', item.sore)
            })
            this.questionClassify()
            console.log('questionList', this.questionList)
            console.log(this.questionList)
            this.editPaperVisible = showVisible
        },
        closeQuestionList() {

            this.editPaperVisible = false
        },
        choicePaperHandle() {

            this.editPaperVisible = true
        },
        cancel() {

            this.$confirm('确定离开此页面吗', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
              this.dialogVisible = false;
            })
        },
        onSubmit() {

            this.submitLoading = true
            if (this.questionList.length < 1) {
                this.$message({ message: '请选择试题', type: 'warning' });
                this.submitLoading = false
                return
            }
            this.form.examCorrelationsList = []
            this.questionList.forEach(item => {
                this.form.examSubjectList = this.questionList
            })
            console.log(JSON.stringify(this.form))
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.id) {
                        updateTestPaper(this.form).then(resp => {
                            this.msgSuccess("修改成功");
                            this.cancel()
                            this.submitLoading = false
                        }).catch(function () {
                            this.submitLoading = false
                        })


                    } else {
                        addTestPaper(this.form).then(resp => {
                            this.msgSuccess("新增成功");
                            this.cancel()
                            this.submitLoading = false
                        }).catch(function () {
                            this.submitLoading = false
                        })
                    }
                } else {
                    this.submitLoading = false
                }

            })
        },
        getMajorList() {
            //查询科目
            findBaseSubjectPageList({ pageSize: 100, pageNum: 1, status: 1 }).then(response => {
                this.majorList = response.data.list
            })
        },
        getSubjectList() {
            //查询专业
            subjectList({ pageSize: 100, pageNum: 1, status: 1 }).then(response => {
                this.subjectList = response.data.list
            })
        },
        getMajorLable(val) {

            for (let i = 0; i < this.majorList.length; i++) {
                if (this.majorList[i].id == val) {
                    return this.majorList[i].subjectName
                }
            }
        },
        getSubjectLable(val) {

            for (let i = 0; i < this.subjectList.length; i++) {
                if (this.subjectList[i].id == val) {
                    return this.subjectList[i].subjName
                }
            }
        },
        scrollToposition(key){

            document.querySelector("#"+key).scrollIntoView()
            console.log(key)
        },
    },

};
</script>

<style scoped lang='scss'>
.el-input-number__decrease {
    display: none;
}

.el-input-number__increase {
    display: none;
}

/deep/ .txtDiv p {
    margin-block-start: 0em;
    margin-block-end: 0em;
}

/deep/ .el-collapse-item__header {
    border-bottom: 0px solid #e6ebf5;
    background-color: #e6ebf5;
}

/deep/ .el-collapse-item__arrow {
    margin: 0 8px 0;
}

/deep/ .el-collapse {
    border-top: 0px solid #e6ebf5;
    border-bottom: 0px solid #e6ebf5;
}

/deep/ a {
    text-decoration: none;
}

.titleClsDiv {
    padding: 15px 10px;
    border-radius: 5px;
    background-color: #f5f5f5;
    color: #666;
    font-size: 14px;
}

.qindexDiv {
    margin-top: 10px;
}

/deep/ .el-tag--info {
    padding: 14px;
    line-height: 0px;
    font-size: 14px;
    margin-right: 5px;
    margin-bottom: 5px;
    cursor: pointer;
}</style>
